import 'dart:convert';

import 'package:db_util/db_util.dart';
import 'package:flutter_coin_util/model/wallet_list_model.dart';
import '../constant/common.dart';
import 'aes_util.dart';

class DatabaseUtil {
  /// 数据库表名称集合
  static Future<List<String>> getTableList() async {
    List<Map<String, dynamic>> allTable = await WXDataBaseUtil.getAllTable();

    List<Map<String, dynamic>> tableList = [];
    tableList.addAll(allTable);
    List<String> tableNames = tableList.map((Map<String, dynamic> e) {
      String s1 = e.toString();
      String s2 = s1.substring(1);
      String s3 = s2.substring(0, s2.length - 1);
      String s4 = s3.replaceFirst("name: ", "");
      return s4;
    }).toList();
    tableNames.removeWhere((element) => !element.startsWith("wx_table_"));

    return tableNames;
  }

  /// 当前数据库的表名
  static Future<String> getFirstTableName() async {
    List<Map<String, dynamic>> allTable = await WXDataBaseUtil.getAllTable();

    List<Map<String, dynamic>> tableList = [];
    tableList.addAll(allTable);
    List<String> tableNames = tableList.map((Map<String, dynamic> e) {
      String s1 = e.toString();
      String s2 = s1.substring(1);
      String s3 = s2.substring(0, s2.length - 1);
      String s4 = s3.replaceFirst("name: ", "");
      return s4;
    }).toList();
    tableNames.removeWhere((element) => !element.startsWith("wx_table_"));
    return tableNames[0];
  }

  /// 钱包名称集合
  static Future<List<String>> getWalletNameList() async {
    List<Map<String, dynamic>> allTable = await WXDataBaseUtil.getAllTable();

    List<Map<String, dynamic>> tableList = [];
    tableList.addAll(allTable);
    List<String> tableNames = tableList.map((Map<String, dynamic> e) {
      String s1 = e.toString();
      String s2 = s1.substring(1);
      String s3 = s2.substring(0, s2.length - 1);
      String s4 = s3.replaceFirst("name: ", "");
      return s4;
    }).toList();
    tableNames.removeWhere((element) => !element.startsWith("wx_table_"));

    List<String> walletNameList = tableNames.map((e) {
      return e.replaceFirst("wx_table_", "");
    }).toList();

    return walletNameList;
  }

  /// 当前钱包名称
  static Future<String> getFirstWalletName() async {
    List<Map<String, dynamic>> allTable = await WXDataBaseUtil.getAllTable();

    List<Map<String, dynamic>> tableList = [];
    tableList.addAll(allTable);
    List<String> tableNames = tableList.map((Map<String, dynamic> e) {
      String s1 = e.toString();
      String s2 = s1.substring(1);
      String s3 = s2.substring(0, s2.length - 1);
      String s4 = s3.replaceFirst("name: ", "");
      return s4;
    }).toList();
    tableNames.removeWhere((element) => !element.startsWith("wx_table_"));

    String currentWalletName = tableNames[0].replaceFirst("wx_table_", "");
    return currentWalletName;
  }

  /// 钱包名转换为表名
  static String walletNameToTableName(String wallet) {
    if (wallet == null) {
      return "";
    }
    return "wx_table_$wallet";
  }

  /// 表名转换为钱包名
  static String tableNameToWalletName(String table) {
    if (table.startsWith("wx_table_")) {
      return table.replaceFirst("wx_table_", "");
    }
    return table;
  }

  /// 获取当前钱包助记词,未解密
  static Future getWalletMnemonic({String tableName}) async {
    String wallet = tableName ?? await DatabaseUtil.getFirstTableName();
    return await WXDataBaseUtil.query(wallet, key: Constant.mnemonicString);
  }

  /// 获取钱包是否备份助记词
  static Future getWalletMnemonicBackupStatus({String tableName}) async {
    String wallet = tableName ?? await DatabaseUtil.getFirstTableName();
    return await WXDataBaseUtil.query(wallet, key: Constant.verifiedMnemonic);
  }

  /// 存储钱包币种数据
  static Future saveWalletCoinsData(String tableName, List<CoinsBean> list) async {
    String walletData = json.encode(list).toString();
    await WXDataBaseUtil.insert(tableName, Constant.allCoinListKey, walletData);
  }

  /// 获取钱包币种数据
  static Future getWalletCoinsData(String tableName) async {
    dynamic coinData = await WXDataBaseUtil.query(tableName, key: Constant.allCoinListKey);
    return coinData;
  }

  /// 修改钱包币种数据
  static Future updateWalletCoinsData(String tableName, String data) async {
    return await WXDataBaseUtil.insert(tableName, Constant.allCoinListKey, data);
  }

  /// 删除钱包
  static Future deleteWallet(String tableName) async {
    return await WXDataBaseUtil.deleteTable(tableName);
  }

  /// 存储交易记录
  static Future saveTransferRecord(String tableName, String data) async {
    return await WXDataBaseUtil.insert(tableName, Constant.transferRecordKey, data);
  }

  /// 获取所有币种交易记录
  static Future getAllTransferRecord(String tableName) async {
    return await WXDataBaseUtil.query(tableName, key: Constant.transferRecordKey);
  }

  /// 获取币种交易记录
  static Future<List<CoinDetailModel>> getCoinTransferRecord(String tableName, String coinName) async {
    dynamic transferRecord = await WXDataBaseUtil.query(tableName, key: Constant.transferRecordKey);
    List list = json.decode(transferRecord.toString());
    List<CoinDetailModel> transferRecordList = CoinDetailModel.fromList(list);
    return transferRecordList;
  }

  /// 存储存入/赎回申购记录
  static Future saveDepositRecordData(String tableName, String data) async {
    return await WXDataBaseUtil.insert(tableName, Constant.depositKey, data);
  }

  /// 获取存入/赎回申购记录
  static Future getDepositRecordData(String tableName) async {
    return await WXDataBaseUtil.query(tableName, key: Constant.depositKey);
  }

  /// 存储Defi利息记录
  static Future saveDefiInterestData(String tableName, String data) async {
    return await WXDataBaseUtil.insert(tableName, Constant.defiInterestKey, data);
  }

  /// 获取Defi利息记录
  static Future getDefiInterestData(String tableName) async {
    return await WXDataBaseUtil.query(tableName, key: Constant.defiInterestKey);
  }

  /// 存储cETH记录
  static Future saveCETHData(String tableName, String data) async {
    return await WXDataBaseUtil.insert(tableName, Constant.cETHKey, data);
  }

  /// 获取cETH记录
  static Future getCETHData(String tableName) async {
    return await WXDataBaseUtil.query(tableName, key: Constant.cETHKey);
  }

//  /// 存储存入赎回记录
//  static Future saveDepositRedeemRecordData(String tableName, String data) async{
//    return await WXDataBaseUtil.insert(tableName, Constant.depositRedeemKey, data);
//  }
//
//  /// 获取存入赎回记录
//  static Future getDepositRedeemRecordData(String tableName) async{
//    return await WXDataBaseUtil.query(tableName, key: Constant.depositRedeemKey);
//  }

  /// 获取全部钱包数据
  static Future<List<Map<String, dynamic>>> getAllWalletData() async {
    List<String> tableNames = await getTableList();
    List<Map<String, dynamic>> allWallet = [];

    for (int i = 0; i < tableNames.length; i++) {
      String tableName = tableNames[i];
      Map<String, dynamic> map = {};

      /// 助记词
      dynamic mnemonic = await WXDataBaseUtil.query(tableName, key: Constant.mnemonicString);

      ///是否备份了助记词
      dynamic mnemonicBackup = await WXDataBaseUtil.query(tableName, key: Constant.verifiedMnemonic);

      /// 钱包币种信息
      dynamic coinList = await getWalletCoinsData(tableName);
      print("coinList=====>$coinList");

      /// 钱包交易信息
      dynamic transferRecordList = await getAllTransferRecord(tableName);
      print("transferRecordList=====>$transferRecordList");

      /// 币种兑换记录，待添加

      /// 整合数据
      map[Constant.walletName] = tableName.replaceFirst("wx_table_", "");
      map[Constant.mnemonicString] = mnemonic;
      map[Constant.verifiedMnemonic] = mnemonicBackup;
      map[Constant.allCoinListKey] = coinList;
      map[Constant.transferRecordKey] = transferRecordList;

      allWallet.add(map);
    }
    return Future.value(allWallet);
  }

  /// 获取所有加密助记词列表
  static Future<List<String>> getAllMnemonicList() async {
    List<String> allMnemonicList = [];
    List<Map<String, dynamic>> allTable = await WXDataBaseUtil.getAllTable();

    List<Map<String, dynamic>> tableList = [];
    tableList.addAll(allTable);
    List<String> tableNames = tableList.map((Map<String, dynamic> e) {
      String s1 = e.toString();
      String s2 = s1.substring(1);
      String s3 = s2.substring(0, s2.length - 1);
      String s4 = s3.replaceFirst("name: ", "");
      return s4;
    }).toList();
    tableNames.removeWhere((element) => !element.startsWith("wx_table_"));

    for (int i = 0; i < tableNames.length; i++) {
      var s1 = await WXDataBaseUtil.query(tableNames[i], key: "mnemonic_string");
      allMnemonicList.add(s1.toString());
    }

    return allMnemonicList;
  }

  /// 获取所有加密私钥列表
  static Future<List<String>> getAllPrivateKeyList() async {
    List<String> allPrivateKeyList = [];
    List<Map<String, dynamic>> allTable = await WXDataBaseUtil.getAllTable();

    List<Map<String, dynamic>> tableList = [];
    tableList.addAll(allTable);
    List<String> tableNames = tableList.map((Map<String, dynamic> e) {
      String s1 = e.toString();
      String s2 = s1.substring(1);
      String s3 = s2.substring(0, s2.length - 1);
      String s4 = s3.replaceFirst("name: ", "");
      return s4;
    }).toList();
    tableNames.removeWhere((element) => !element.startsWith("wx_table_"));

    for (int i = 0; i < tableNames.length; i++) {
      dynamic coins = await getWalletCoinsData(tableNames[i]);
      List<CoinsBean> allCoinList = CoinsBean.toList(json.decode(coins.toString()));

      if (allCoinList.length > 0) {
        for (int j = 0; j < allCoinList.length; j++) {
          allPrivateKeyList.add(AESUtil.encryptString(allCoinList[j].privateKey));
        }
      }

      // var s1 = await WXDataBaseUtil.query(tableNames[i], key: "private_key_string");
      // allPrivateKeyList.add(s1.toString());
    }

    return allPrivateKeyList;
  }
}
